import Vue from 'vue'
const { shell } = require('electron')

const readRegVaule = (regPath, callback) => {
    let err = null;
    const registry = require('regedit');
    registry.list(regPath, (error, result) => {
        if (error) {
            if (callback) {
                err = error
                callback(err)
            }
        }
        if (result) {
            let values = result[regPath].values;
            callback(err, values);
        }
    })
}

const openNativeFile = (filePath) => {
    shell.openItem(filePath)
}

Vue.prototype.$openNativeFile = (filePath) => {
    shell.openItem(filePath)
}

Vue.prototype.$executeCmd = function(cmdStr, cmdPath){
    const exec = require('child_process').exec
    let workerProcess = exec(cmdStr, { cwd: cmdPath })
    // 打印正常的后台可执行程序输出
    workerProcess.stdout.on('data', function (data) {
        console.log('stdout: ' + data)
    })
    // 打印错误的后台可执行程序输出
    workerProcess.stderr.on('data', function (data) {
        console.log('stderr: ' + data)
    })
    // 退出之后的输出
    workerProcess.on('close', function (code) {
        console.log('out code：' + code)
    })
}

Vue.prototype.$openPPT = (pptPath, isSlideShow=false) => {
    const exec = require('child_process').exec
    // 读取注册表，获取PPT的安装路径
    readRegVaule('HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\powerpnt.exe', function (error, values) {
        exec(pptPath);
        if (error) {
            // 注册表读取失败，使用系统默认方式打开PPT
            // openNativeFile(pptPath);
        }
        if (values) {
            try {
                // 获取POWERPNT.exe的路径
                let powerPntPath = values.Path.value + '\\POWERPNT.EXE';
                let args = [pptPath];
                if (isSlideShow) {
                    args = ['/s', pptPath];
                }
                executeExe(powerPntPath, args);
            } catch (error) {
                // 打开失败，使用系统默认方式打开PPT
                // openNativeFile(pptPath);
            }
        }
        else {
            // 打开失败，使用系统默认方式打开PPT
            // openNativeFile(pptPath);
        }
    })
}

Vue.prototype.$executeCmd = function(cmdStr, cmdPath){
    const exec = require('child_process').exec
    let workerProcess = exec(cmdStr, { cwd: cmdPath })
    // 打印正常的后台可执行程序输出
    workerProcess.stdout.on('data', function (data) {
        console.log('stdout: ' + data)
    })
    // 打印错误的后台可执行程序输出
    workerProcess.stderr.on('data', function (data) {
        console.log('stderr: ' + data)
    })
    // 退出之后的输出
    workerProcess.on('close', function (code) {
        console.log('out code：' + code)
    })
}
